import api from './api'
import DeviceStorage from '../utils/DeviceStorage'
import define from '../utils/define'
import Tips from 'react-native-root-tips';
import {DeviceEventEmitter} from "react-native";

let common_url = api.baseUrl;  //服务器地址
let token = ''
DeviceStorage.get(define.token).then((args) => {
    if (args) {
        token = 'Bearer ' + args;
    } else {
        token = null;
    }
})
DeviceEventEmitter.addListener('loginToken', (args) => {
    if (args) {
        token = 'Bearer ' + args;
    } else {
        token = null;
    }
});
DeviceEventEmitter.addListener('loginOut', () => {
    token = null;
});
Tips.setDefaultOptions({
    showLoading: true,
    backgroundColor: 'gray',
    opacity: 0.95,
    textColor: 'white',
    durations: 1000

    // setting image you like
    // imageLoading: require('xxxxxxxxxx'),
    // imageSuccess: require('xxxxxxxxxx'),
    // imageFail: require('xxxxxxxxxx'),
    // imageInfo: require('xxxxxxxxxx'),
    // imageWarn: require('xxxxxxxxxx'),
});
/**
 * @param {string} url 接口地址
 * @param {string} method 请求方法：GET、POST，只能大写
 * @param {JSON} [params=''] body的请求参数，默认为空
 * @return 返回Promise
 */


export function fetchPostRequest(url, method, params) {
    let header = {
        // 'Accept': 'application/json',
        // "Content-Type": "application/x-www-form-urlencoded",
        "Authorization": token,  //用户登陆后返回的token，某些涉及用户数据的接口需要在header中加上token
    };


    console.log('request url:', url, params, header);  //打印请求参数

    return new Promise(function (resolve, reject) {
        let formData = new FormData();
        for (var key in params) {
            formData.append(key, params[key]);
        }
        console.log('sssssdd', formData)
        fetch(common_url + url, {
            method: method,
            headers: header,
            body: formData,   //body参数，通常需要转换成字符串后服务器才能解析
        }).then((response) => response)
            .then((responseData) => {
                // console.log('res:',url, responseData);   //网络请求成功返回的数据
                console.log('res:', url, responseData);  //网络请求成功返回的数据
                let data = JSON.parse(responseData._bodyText)
                if (data.code) {
                    reject(data.message);
                } else {
                    resolve(data);
                }
            })
            .catch((err) => {
                console.log('err:', url, err);   //网络请求失败返回的数据
                reject(err);
            });
    });
}
export function fetchGetRequest(url, method, params) {
    let header = {
        // 'Accept': 'application/json',
        // "Content-Type": "application/x-www-form-urlencoded",
        "Authorization": token,  //用户登陆后返回的token，某些涉及用户数据的接口需要在header中加上token
    };
    console.log('token', token)
    var meth_head = {}
    if (token == null) {
        meth_head = {
            method: method,
        }
    } else {
        meth_head = {
            method: method,
            headers: header,
        }
    }

    //如果网络请求中没有参数
    if (params) {
        let paramsArray = [];
        //拼接参数
        Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]))
        if (url.search(/\?/) === -1) {
            url += '?' + paramsArray.join('&')
        } else {
            url += '&' + paramsArray.join('&')
        }
    }
    console.log('res:', url,);  //网络请求成功返回的数据
    return new Promise(function (resolve, reject) {

        fetch(common_url + url, meth_head).then((response) => response)
            .then((responseData) => {
                console.log('res:', url, responseData);  //网络请求成功返回的数据
                if (responseData.status == 200) {
                    let data = JSON.parse(responseData._bodyText)
                    if (data.code) {
                        reject(data.message);
                    } else {
                        resolve(data);
                    }
                } else {
                    console.log('500', responseData._bodyText)
                    Tips.showFail('服务器开小差了...', {mask: true})
                }
            })
            .catch((err) => {
                // console.log('err:',url, err);   //网络请求失败返回的数据
                reject(err);
            });
    });
}

export function uploadImage(params) {
    return new Promise(function (resolve, reject) {

        let formData = new FormData();
        let file = {uri: params.path, type: 'image/jpeg', name: params.fileName};
        formData.append("avatar", file);
        fetch(api.baseUrl + 'api/upload/avatar', {
            method: 'POST',
            headers: {
                'Content-Type': 'multipart/form-data',
                'Authorization': token,
            },
            body: formData,
        }).then((response) => response)
            .then((responseData) => {

                console.log('uploadImage', responseData);
                if (responseData.status == 200) {
                    resolve(JSON.parse(responseData._bodyText));
                } else {
                    reject(responseData.statusText);
                }
            })
            .catch((err) => {
                console.log('err', err);
                reject(err);
            });

    });
}

/**
 * 上传课程作业图片
 * @param params
 * @returns {Promise}
 */
// export function uploadHomeworkImage(imgAry) {
//     let formData = new FormData();
//     for (var i = 0; i
//     < imgAry.length; i++) {
//         let file = {uri: imgAry[i], type: 'multipart/form-data', name: 'image.png'};   //这里的key(uri和type和name)不能改变,
//         formData.append("student_file", file);   //这里的files就是后台需要的key
//     }
//
//     formData.append("lesson_id", this.state.homeworkItem.lesson_id)
//     formData.append("course_id", this.state.homeworkItem.course_id)
//
//     fetch(common_url + url, {
//         method: 'POST',
//         headers: {
//             'Content-Type': 'multipart/form-data',
//             'Authorization': token,
//         },
//         body: formData,
//     })
//         .then((response) => response.text())
//         .then((responseData) => {
//             console.log('responseData', responseData);
//         })
//         .catch((error) => {
//             console.error('error', error)
//         });
// }


export function uploadFile(params) {
    return new Promise(function (resolve, reject) {

        let formData = new FormData();
        let file = {uri: params.path, type: 'image/jpeg', name: params.fileName};
        formData.append("file", file);
        fetch('https://t.api.jkzaixian.com/api/upload/file', {
            method: 'POST',
            headers: {
                'Content-Type': 'multipart/form-data',
                'Authorization': token,
            },
            body: formData,
        }).then((response) => response)
            .then((responseData) => {

                console.log('uploadfile', responseData);
                if (responseData.status == 200) {
                    resolve(JSON.parse(responseData._bodyText));
                } else {
                    reject(responseData.statusText);
                }
            })
            .catch((err) => {
                console.log('err', err);
                reject(err);
            });

    });
}

